package com.ruge._08_springboot_springdata_jpa.controller._03_mapping._07_casecade;

import com.ruge._08_springboot_springdata_jpa.Application;
import com.ruge._08_springboot_springdata_jpa.controller._03_mapping._03_manyToOne.ManyToOneDeptModel;
import com.ruge._08_springboot_springdata_jpa.controller._03_mapping._03_manyToOne.ManyToOneEmpModel;
import com.ruge._08_springboot_springdata_jpa.controller._03_mapping._06_extends.ExtendsBook;
import com.ruge._08_springboot_springdata_jpa.controller._03_mapping._06_extends.ExtendsCloth;
import com.ruge._08_springboot_springdata_jpa.controller._03_mapping._06_extends.ExtendsProduct;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.Arrays;
import java.util.List;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2019-07-05  22:43
 * 描述 ：级联的测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)//这里是启动类
public class TestCasecade {
    @Autowired
    private EntityManager entityManager;

    @Test
    @Transactional
    public void testSave() {
        CasecadeOrderBill orderBill = new CasecadeOrderBill("9527");
        CasecadeOrderBillItem goods1 = new CasecadeOrderBillItem("商品1");
        CasecadeOrderBillItem goods2 = new CasecadeOrderBillItem("商品2");
        orderBill.setItems(Arrays.asList(goods1,goods2));
        entityManager.persist(orderBill);
        entityManager.flush();
    }

    @Test
    @Transactional
    public void testUpdate() {
        //先查询到需要编辑的订单信息
        CasecadeOrderBill bill = entityManager.find(CasecadeOrderBill.class, 8);
        List<CasecadeOrderBillItem> items = bill.getItems();

        //添加一个新的明细
        items.add(new CasecadeOrderBillItem("newProductName"));
        //更新订单明细
        //修改一个明细的信息
        items.get(0).setProduceName("updateProduceName");
        //删除一个明细信息
        //默认情况,JPA只会删除对应的关系,不会将关联的明细信息删除
        //在这里,我们将没有了关系数据的明细信息称之为孤儿,所以,此时是需要将这些数据删除的
        //items.remove(0);
        //merge:可以执行更新和保存操作
        //当对象存在OID的时候,执行更新,反之,执行保存
        entityManager.merge(bill);
        entityManager.flush();
    }

    @Test
    @Transactional
    public void testDelete() {
        CasecadeOrderBill stuModel1 =   entityManager.find(CasecadeOrderBill.class,1);
        entityManager.remove(stuModel1);
        entityManager.flush();
    }

    @Test
    @Transactional
    public void testSelect() {
       List list = entityManager.createQuery("select  t from CasecadeOrderBill t").getResultList();
       list.forEach(System.out::println);
    }
}
